package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	OrderMapper orderMapper;
	@Autowired
	OrderDetailMapper orderDetailMapper;
	@Autowired
	AddressBookMapper addressBookMapper;
	@Autowired
	ShoppingCartMapper shoppingCartMapper;
	@Autowired
	UserMapper userMapper;
	@Autowired
	WeChatPayUtil weChatPayUtil;
	@Autowired
	WebSocketServer webSocketServer;


	/**
	 * 提交订单
	 *
	 * @param ordersSubmitDTO
	 * @return
	 */
	@Override
	@Transactional
	public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
		// 处理业务异常（未提交地址和购物车没有商品）
		// 从表里查询前端发来的地址id
		AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
		if (addressBook == null) {
			// 没有查到地址，抛出异常
			throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
		}
		// 数据封装
		ShoppingCart shoppingCart = new ShoppingCart();
		shoppingCart.setUserId(BaseContext.getCurrentId());
		// 从表里查看当前用户购物车是否有商品
		List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
		if (shoppingCartList == null || shoppingCartList.size() == 0) {
			throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
		}
		// 向订单表插入一条数据
		// 数据封装
		Orders orders = new Orders();
		BeanUtils.copyProperties(ordersSubmitDTO, orders);
		orders.setOrderTime(LocalDateTime.now());
		orders.setPayStatus(Orders.UN_PAID);
		orders.setStatus(Orders.PENDING_PAYMENT);
		orders.setUserId(BaseContext.getCurrentId());
		orders.setNumber(String.valueOf(System.currentTimeMillis()));
		orders.setPhone(addressBook.getPhone());
		orders.setConsignee(addressBook.getConsignee());
		orders.setAddress(addressBook.getDetail());

		orderMapper.insert(orders);
		// 向订单明细表插入数据
		List<OrderDetail> orderDetailList = new ArrayList<>();
		for (ShoppingCart cart : shoppingCartList) {
			// 订单明细，数据准备
			OrderDetail orderDetail = new OrderDetail();
			BeanUtils.copyProperties(cart, orderDetail);
			// 设置当前订单明细关联的订单id
			orderDetail.setOrderId(orders.getId());
			orderDetailList.add(orderDetail);
		}
		// 批量插入订单明细
		orderDetailMapper.insert(orderDetailList);
		// 清空购物车数据
		shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
		// 封装VO数据
		OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
				.id(orders.getId())
				.orderTime(orders.getOrderTime())
				.orderNumber(orders.getNumber())
				.orderAmount(orders.getAmount())
				.build();
		return orderSubmitVO;
	}

	/**
	 * 订单支付
	 *
	 * @param ordersPaymentDTO
	 * @return
	 */
	public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {


		// 调用微信支付接口，生成预支付交易单(本项目不能用）
		// JSONObject jsonObject = weChatPayUtil.pay(
		// 		ordersPaymentDTO.getOrderNumber(), //商户订单号
		// 		new BigDecimal(0.01), //支付金额，单位 元
		// 		"苍穹外卖订单", //商品描述
		// 		user.getOpenid() //微信用户的openid
		// );
		//
		// if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
		// 	throw new OrderBusinessException("该订单已支付");
		// }
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code", "ORDERPAID");
		OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
		vo.setPackageStr(jsonObject.getString("package"));



		// 本项目因不能用微信支付，直接在点击订单支付后，修改订单为已支付
		// 在mapper再定义一个方法，通过订单号和用户id查询订单
		Long userId=BaseContext.getCurrentId();
		String orderNumber=ordersPaymentDTO.getOrderNumber();
		Orders ordersDB = orderMapper.getByNumberAndUserId(userId, orderNumber);

		// 根据id更新订单的状态、支付方式、支付状态、结账时间
		Orders orders = Orders.builder()
				.id(ordersDB.getId())
				.number(ordersPaymentDTO.getOrderNumber())
				.status(Orders.TO_BE_CONFIRMED)
				.payStatus(Orders.PAID)
				.checkoutTime(LocalDateTime.now())
				.build();

		orderMapper.update(orders);
		//有客户支付订单了，使用websocket对象向客户端推送消息
		//封装type，orderId,content
		Map map = new HashMap<>();
		map.put("type",1);//1表示来单提醒，2表示客户催单
		map.put("orderId",ordersDB.getId());
		map.put("content","订单号"+orderNumber);

		//转成json格式
		String json= JSONObject.toJSONString(map);
		//向页面推送来单提醒
		webSocketServer.sendToAllClient(json);


		return vo;
	}

	/**
	 * 支付成功，修改订单状态,不能用
	 *
	 * @param outTradeNo
	 */
	public void paySuccess(String outTradeNo) {

		// 根据订单号查询订单
		Orders ordersDB = orderMapper.getByNumberAndUserId(BaseContext.getCurrentId(),outTradeNo);

		// 根据订单id更新订单的状态、支付方式、支付状态、结账时间
		Orders orders = Orders.builder()
				.id(ordersDB.getId())
				.status(Orders.TO_BE_CONFIRMED)
				.payStatus(Orders.PAID)
				.checkoutTime(LocalDateTime.now())
				.build();

		orderMapper.update(orders);
	}

	/**
	 * 分页查询历史订单
	 *
	 * @param page
	 * @param pageSize
	 * @param status
	 * @return
	 */
	@Override
	public PageResult page(Integer page, Integer pageSize, Integer status) {
		PageHelper.startPage(page, pageSize);
		// 数据准备，封装
		OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
		ordersPageQueryDTO.setStatus(status);
		ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
		// 根据用户id和状态查询订单
		Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
		List<OrderVO> orderVOListlist = new ArrayList<>();
		if (ordersPage != null && ordersPage.getTotal() > 0) {
			// 遍历
			for (Orders orders : ordersPage) {
				Long orderId = orders.getId();
				// 查询订单明细
				List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
				// 数据封装
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				orderVO.setOrderDetailList(orderDetails);
				orderVOListlist.add(orderVO);
			}
		}
		return new PageResult(ordersPage.getTotal(), orderVOListlist);
	}

	/**
	 * 根据订单id获取订单和订单明细
	 *
	 * @param id
	 * @return
	 */
	@Override
	public OrderVO getByid(Long id) {
		// 获取订单
		OrderVO orderVO = orderMapper.getByid(id);
		// 获取订单详细
		orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(id));
		return orderVO;
	}

	/**
	 * 用户取消订单
	 * @param id
	 */
	@Override
	public void cancel(Long id) {
		//查询订单，查看订单是否存在，不存在报错
		OrderVO order = orderMapper.getByid(id);
		if (order == null) {
			new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
		}
		//查看订单状态，只有在待付款和待接单时可取消，否则报错
		if(order.getStatus()>2){
			new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		//订单为待付款时,调用微信接口，申请退款（本项目无法使用），只能改支付状态
		if(order.getStatus().equals(Orders.TO_BE_CONFIRMED)){
			//调用微信支付退款接口（本项目无法使用）
			// weChatPayUtil.refund(
			// 		order.getNumber(), //商户订单号
			// 		order.getNumber(), //商户退款单号
			// 		new BigDecimal(0.01),//退款金额，单位 元
			// 		new BigDecimal(0.01));//原订单金额


			//修改支付状态
			orderMapper.setPayStatus(Orders.REFUND,id);
		}
		//改订单状态和取消原因和取消时间
		//数据准备，封装数据
		Orders orders = new Orders();
		orders.setId(id);
		orders.setStatus(Orders.CANCELLED);
		orders.setCancelReason("用户取消");
		orders.setCancelTime(LocalDateTime.now());
		orderMapper.update(orders);
	}

	/**
	 * 顾客再来一单
	 * @param id
	 */
	@Override
	public void repetition(Long id) {
		//获取订单明细集合
		List<OrderDetail> orderDetailList= orderDetailMapper.getByOrderId(id);
		// 将订单详情对象转换为购物车对象
		List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
			ShoppingCart shoppingCart = new ShoppingCart();

			// 将原订单详情里面的菜品信息重新复制到购物车对象中
			BeanUtils.copyProperties(x, shoppingCart, "id");
			shoppingCart.setUserId(BaseContext.getCurrentId());
			shoppingCart.setCreateTime(LocalDateTime.now());

			return shoppingCart;
		}).collect(Collectors.toList());

		// 将购物车对象批量添加到数据库
		shoppingCartMapper.insertBatch(shoppingCartList);
	}

	/**
	 * 根据条件查询订单
	 * @param ordersPageQueryDTO
	 * @return
	 */
	@Override
	public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
		PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
		Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
		List<OrderVO> orderVOList = getOrderVOList(page);

		return new PageResult(page.getTotal(), orderVOList);
	}

	/**
	 * 将Orders集合转化为OrderVO集合
	 * @param page
	 * @return
	 */
	private List<OrderVO> getOrderVOList(Page<Orders> page) {
		List<OrderVO> orderVOList = new ArrayList<>();
		//从Page集合中得到Orders集合
		List<Orders> ordersList = page.getResult();
		//判断集合是否为空
		if(ordersList != null && ordersList.size() > 0){
			//遍历ordersList
			for (Orders orders : ordersList) {
				//数据封装
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				//使用方法得到orderDishs属性
				String orderDishs=getOrderDishs(orders);
				orderVO.setOrderDishes(orderDishs);
				//将数据添加到orderVO集合中
				orderVOList.add(orderVO);
			}
		}
		return orderVOList;
	}

	/**
	 * 把订单菜品详细集合，拼接成字符串
	 * @param orders
	 * @return
	 */
	private String getOrderDishs(Orders orders) {
		//获得订单的菜品详细集合
		List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
		//把每条菜品详细信息转化为字符串集合(例：格式"宫保鸡丁*3”)
		List<String> orderDishList = orderDetailList.stream().map(x->{
			String orderDish=x.getName()+"*"+x.getNumber()+";";
					return orderDish;
		}).collect(Collectors.toList());
		//把字符串集合连接一起
		return String.join("",orderDishList);
	}

	/**
	 * 获取各个状态的订单数量
	 * @return
	 */
	@Override
	public OrderStatisticsVO statistics() {
		OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
		//查询为待接单，已接单，派送中的订单数量
		Integer toBeConfirmed=orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
		Integer confirmed=orderMapper.countStatus(Orders.CONFIRMED);
		Integer deliveryInProgress=orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
		//数据封装
		orderStatisticsVO.setConfirmed(confirmed);
		orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
		orderStatisticsVO.setToBeConfirmed(toBeConfirmed);

		return orderStatisticsVO;
	}

	/**
	 * 商家接单
	 * @param ordersConfirmDTO
	 */
	@Override
	public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
		//数据封装
		Orders orders =new Orders();
		orders.setId(ordersConfirmDTO.getId());
		orders.setStatus(Orders.CONFIRMED);
		orderMapper.update(orders);
	}

	/**
	 * 商家拒单
	 * @param ordersRejectionDTO
	 */
	@Override
	public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
		//判断订单状态，只能为待接单才能拒单,否则抛出异常
		OrderVO orderVO = orderMapper.getByid(ordersRejectionDTO.getId());
		if(orderVO==null|| orderVO.getStatus()!=2){
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		//判断支付状态是否为已支付，是则拒单需要调用微信退款接口退款（本项目不能用）
		if(orderVO.getPayStatus().equals(Orders.PAID)){
			// 调用微信接口退款(本项目不能用)
			// String refund = weChatPayUtil.refund(
			// 		ordersDB.getNumber(),
			// 		ordersDB.getNumber(),
			// 		new BigDecimal(0.01),
			// 		new BigDecimal(0.01));
			// log.info("申请退款：{}", refund);
		}
		//修改订单状态为已拒单，修改取消原因和取消时间
		Orders orders = Orders.builder()
				.id(ordersRejectionDTO.getId())
				.status(Orders.CANCELLED)
				.cancelReason(ordersRejectionDTO.getRejectionReason())
				.cancelTime(LocalDateTime.now())
				.build();
		orderMapper.update(orders);
	}

	/**
	 * 商家取消订单
	 * @param ordersCancelDTO
	 */
	@Override
	public void cancel(OrdersCancelDTO ordersCancelDTO) {
		OrderVO order = orderMapper.getByid(ordersCancelDTO.getId());
		//判断订单的支付状态，如果已支付需要退款
		if(order.getPayStatus().equals(Orders.PAID)){
			//调用微信退款接口（本项目不能用）
			// String refund = weChatPayUtil.refund(
			// 		ordersDB.getNumber(),
			// 		ordersDB.getNumber(),
			// 		new BigDecimal(0.01),
			// 		new BigDecimal(0.01));
			// log.info("申请退款：{}", refund);

		}
		//数据封装
		Orders orders=Orders.builder()
				.id(ordersCancelDTO.getId())
				.cancelReason(ordersCancelDTO.getCancelReason())
				.cancelTime(LocalDateTime.now())
				.build();
		//更新订单状态，订单取消原因，订单取消时间
		orderMapper.update(orders);
	}

	/**
	 * 订单派送
	 * @param id
	 */
	@Override
	public void delivery(Long id) {
		OrderVO order = orderMapper.getByid(id);
		//判断订单是否存在，判断订单状态是否为已接单（待派送）
		if(order==null||!order.getStatus().equals(Orders.CONFIRMED)){
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		//修改订单状态为派送中
		Orders orders=new Orders();
		orders.setId(id);
		orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
		orderMapper.update(orders);
	}

	/**
	 * 完成订单
	 * @param id
	 */
	@Override
	public void complete(Long id) {
		OrderVO order = orderMapper.getByid(id);
		//判断订单是否存在，判断订单状态是否为派送中
		if(order==null||!order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		//修改订单状态为已完成
		Orders orders=new Orders();
		orders.setId(id);
		orders.setStatus(Orders.COMPLETED);
		orderMapper.update(orders);
	}

	/**
	 * 用户催单
	 * @param id
	 */
	@Override
	public void reminder(Long id) {
		//根据id查询订单
		Orders orders=orderMapper.getByid(id);

		//判断订单是否存在
		if(orders==null){
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		//封装数据，type，orderId,content
		Map map=new HashMap();
		map.put("type",2);//1为来单提醒，2为顾客催单
		map.put("orderId",id);
		map.put("content","订单号"+orders.getNumber());
		String json= JSONObject.toJSONString(map);
		//向管理端推送消息
		webSocketServer.sendToAllClient(json);
	}
}
